package com.qc31.monitorlib.ui.carmonitor

import android.view.View
import android.widget.TextView
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.qc31.baselib.base.LazyLoadSirFragment
import com.qc31.baselib.custom.timer.CustomDatePicker
import com.qc31.baselib.custom.timer.DateFormatUtils
import com.qc31.baselib.databinding.IncludeSelectSureBinding
import com.qc31.baselib.loadsie.EmptyCallback
import com.qc31.baselib.rx.LiveDataBus
import com.qc31.baselib.utils.startActivityTo
import com.qc31.comlib.Keys
import com.qc31.comlib.TimeUtil
import com.qc31.comlib.adapter.ChooseTimeAdapter
import com.qc31.comlib.databinding.IncludeChooseFastTimeBinding
import com.qc31.comlib.entity.KeyValue
import com.qc31.comlib.popup.KeyValuePopup
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.FragmentCarHistoryVideoBinding
import com.qc31.monitorlib.databinding.IncludeTabChangeBinding
import com.qc31.monitorlib.uitls.DataUtil

/** @Author Jasper @Time 2020/7/22 @Desc 车辆 历史视频 */
class CarHistoryVideoFragment :
    LazyLoadSirFragment<FragmentCarHistoryVideoBinding>(FragmentCarHistoryVideoBinding::inflate) {

    private lateinit var mTureVB: IncludeSelectSureBinding
    private lateinit var mFastVB: IncludeChooseFastTimeBinding
    private lateinit var mTabChangeVB: IncludeTabChangeBinding

    private val mActivityVM by activityViewModels<CarMonitorViewModel>()

    private val mViewModel by viewModels<CarHistoryVideoViewModel>()

    private val mKeyValuePopup by lazy { KeyValuePopup(requireActivity()) }

    override fun initView(view: View) {
        mTureVB = IncludeSelectSureBinding.bind(binding.root)
        mFastVB = IncludeChooseFastTimeBinding.bind(binding.root)
        mTabChangeVB = IncludeTabChangeBinding.bind(binding.root)
        binding.lrvChooseCar.visibility = View.GONE
    }

    override fun initData() {
        mViewModel.init(
            getString(R.string.desc_video_all_pass),
            getString(R.string.desc_video_pass)
        )
        mActivityVM.carId.observe(this) {
            mViewModel.carId = it
        }

        mActivityVM.videos.observe(this) {
            mViewModel.videos = it ?: ""
            if (it.isNullOrEmpty()) {
                loadService.setCallBack(EmptyCallback::class.java) { _, view ->
                    val empty = view.findViewById<TextView>(R.id.tv_empty)
                    empty.text = getString(R.string.desc_choose_not_video_car)
                }
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                loadService.showSuccess()
                initView()
            }
        }
        mActivityVM.carName.observe(this) { mViewModel.carName = it }

        if (mViewModel.carId.isEmpty()) {
            loadService.setCallBack(EmptyCallback::class.java) { context, view ->
                val empty = view.findViewById<TextView>(R.id.tv_empty)
                empty.text = getString(R.string.hint_toast_choose_car)
            }
            loadService.showCallback(EmptyCallback::class.java)
        }
        handleModel()
    }


    private fun initView() {
        binding.lrTvPass.setRightText(mViewModel.videoPassList[mViewModel.tmnPass].value)
        binding.lrTvRes.setRightText(DataUtil.getVideoRes(requireContext())[mViewModel.tmnRes].value)
        binding.lrTvStream.setRightText(DataUtil.getVideoStream(requireContext())[mViewModel.tmnStream].value)
        binding.lrTvStorage.setRightText(DataUtil.getVideoStorage(requireContext())[mViewModel.tmnStorage].value)
        mKeyValuePopup.setCallBack(mPopupCallBack)
    }

    override fun initEvent() {
        mTabChangeVB.rdbVideoTmn.setOnClickListener {
            mViewModel.isTmn = true
            binding.lrTvStream.visibility = View.VISIBLE
            binding.lrTvStorage.visibility = View.VISIBLE
            binding.lrTvRes.visibility = View.VISIBLE
        }
        mTabChangeVB.rdbVideoPlate.setOnClickListener {
            mViewModel.isTmn = false
            binding.lrTvStream.visibility = View.GONE
            binding.lrTvStorage.visibility = View.GONE
            binding.lrTvRes.visibility = View.GONE
        }
        mTureVB.tvSure.setOnClickListener {
            mViewModel.getTmVideosInfo(
                binding.lrvStartTime.getRightText(),
                binding.lrvEndTime.getRightText()
            )
        }
        binding.lrTvPass.setOnClickListener {
            mViewModel.popupType = 0
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_passes),
                mViewModel.videoPassList,
                mViewModel.tmnPass
            )
        }
        binding.lrTvRes.setOnClickListener {
            mViewModel.popupType = 1
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_res_type),
                DataUtil.getVideoRes(requireContext()),
                mViewModel.tmnRes
            )
        }
        binding.lrTvStream.setOnClickListener {
            mViewModel.popupType = 2
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_stream_type),
                DataUtil.getVideoStream(requireContext()),
                mViewModel.tmnStream
            )
        }

        binding.lrTvStorage.setOnClickListener {
            mViewModel.popupType = 3
            mKeyValuePopup.showPopupWindow(
                requireActivity().window.decorView,
                getString(R.string.desc_video_storage_type),
                DataUtil.getVideoStorage(requireContext()),
                mViewModel.tmnStorage
            )
        }

        binding.lrvStartTime.rightClick().autoDispose(scopeProvider).subscribe {
            mViewModel.isStart = true
            mDatePicker.show(binding.lrvStartTime.getRightText())
        }

        binding.lrvEndTime.rightClick().autoDispose(scopeProvider).subscribe {
            mViewModel.isStart = false
            mDatePicker.show(binding.lrvEndTime.getRightText())
        }

    }


    /** 资源设置 */
    private val mPopupCallBack: KeyValuePopup.CallBack = object : KeyValuePopup.CallBack {
        override fun onBack(entity: KeyValue, index: Int) {
            when (mViewModel.popupType) {
                0 -> {
                    mViewModel.tmnPass = index
                    mViewModel.pass = entity.key
                    binding.lrTvPass.setRightText(entity.value)
                }
                1 -> {
                    mViewModel.tmnRes = index
                    binding.lrTvRes.setRightText(entity.value)
                }
                2 -> {
                    mViewModel.tmnStream = index
                    binding.lrTvStream.setRightText(entity.value)
                }
                3 -> {
                    mViewModel.tmnStorage = index
                    binding.lrTvStorage.setRightText(entity.value)
                }
            }
        }
    }

    private fun handleModel() {
        mViewModel.entitySub.hide().autoDispose(scopeProvider)
            .subscribe {
                startActivityTo<HistoryVideoInfoActivity>(requireActivity()) {
                    putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                    putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                    putExtra("isTmn", mViewModel.isTmn)
                }
                LiveDataBus.get().with("key_history_video").postValue(it)
            }

        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        mFastVB.recyclerWrap.layoutManager = GridLayoutManager(context, 4)
        mFastVB.recyclerWrap.adapter = mAdapter.apply {
            setNewInstance(mViewModel.timeList)
            setOnItemClickListener { adapter, view, position ->
                index = position
                notifyDataSetChanged()
                mViewModel.chooseTime(position)
            }
        }
        mViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            binding.lrvStartTime.setRightText(it)
        }

        mViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            binding.lrvEndTime.setRightText(it)
        }
    }

    //*********************************时间选择相关*****************************************************
    private val mAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }
    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            requireContext(), callback, TimeUtil.normalDate, mViewModel.nowTimeFormat(), true
        ).apply {
            setCanShowPreciseTime(true)
        }
    }
    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, true)

            if (mViewModel.isStart) {
                binding.lrvStartTime.setRightText(time)
            } else {
                binding.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }
}